package com.avic.rong.fragment;


import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.avic.rong.BuildConfig;
import com.avic.rong.MainActivity;
import com.avic.rong.R;
import com.avic.rong.api.HttpPostService;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.NetWorkUtils;
import com.avic.rong.utils.SDCardUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.customWedgit.SheetDialog;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.avic.rong.wedgit.permissionschecker.PermissionChecker;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.utils.AppUtils;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.orhanobut.logger.Logger;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import wendu.dsbridge.DWebView;
import wendu.dsbridge.OnReturnValue;

import static com.avic.rong.activity.product.OnlineCServiceActivity.recycleBitmap;

/**
 * A simple {@link Fragment} subclass.
 */
public class ServiceNewsFragment extends BaseLazyFragment {


    @BindView(R.id.webview)
    DWebView webview;

    @BindView(R.id.loading_layout)
    LoadingLayout loading_layout;
    private View view;
    private Unbinder unbinder;
    private ValueCallback<Uri> mUploadCallBack;
    private SheetDialog sheetDialog;
    private PermissionChecker permissionChecker;
    private ValueCallback<Uri[]> mUploadCallBackAboveL;
    private String[] PERMISSIONS = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private String cameraPath;
    private static final int TAKE_CAMERA_PHOTO = 200;
    private int REFRESH = 200;

    public ServiceNewsFragment() {
        // Required empty public constructor
    }



    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(getActivity());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.CART_BROADCAST");
        BroadcastReceiver mItemViewListClickReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent){
                String msg = intent.getStringExtra("data");
                if("refresh".equals(msg)){
                    loadWebView();
                }
            }
        };
        broadcastManager.registerReceiver(mItemViewListClickReceiver, intentFilter);
    }


    public void clearCache(){
        //清空所有Cookie
        CookieSyncManager.createInstance(getContext());  //Create a singleton CookieSyncManager within a context
        CookieManager cookieManager = CookieManager.getInstance(); // the singleton CookieManager instance
        cookieManager.removeAllCookie();// Removes all cookies.
        CookieSyncManager.getInstance().sync(); // forces sync manager to sync now

        webview.setWebChromeClient(null);
        webview.setWebViewClient(null);
        webview.getSettings().setJavaScriptEnabled(false);
        webview.clearCache(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment/cservice
        View inflate = inflater.inflate(R.layout.fragment_service_news, container, false);
        unbinder = ButterKnife.bind(this, inflate);

        loading_layout.setStatus(LoadingLayout.LOADING);
        loading_layout.hideReturnButton();

        loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loading_layout.setStatus(LoadingLayout.LOADING);
                reLoad();
            }

            @Override
            public void onReturn(View v) {
                getActivity().onBackPressed();
            }
        });

        return inflate;
    }


    private void reLoad() {
        if (NetWorkUtils.isConnectInternet(getContext())){
            loading_layout.setStatus(LoadingLayout.SUCCESS);
        }else {
            loading_layout.setStatus(LoadingLayout.ERROR);
        }
        webview.reload();
    }

    private void loadWebView() {
        WebSettings setting = webview.getSettings();
        setting.setCacheMode(WebSettings.LOAD_NO_CACHE);
        setting.setJavaScriptEnabled(true);
        setting.setBlockNetworkImage(false);//解决图片不显示
        webview.addJavascriptObject(this, null);

        webview.setWebChromeClient(new MyWebChromeClient());
        permissionChecker = new PermissionChecker((MainActivity)getContext());

        try {
            String token = URLEncoder.encode(SharedPreferencesUtil.getLoginToken(), "UTF-8");
            webview.loadUrl(AppUtils.BASE_URL + "cservice?token=" +token);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        webview.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                    updateKFuState();
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                if (NetWorkUtils.isConnectInternet(getContext())){
                    loading_layout.setStatus(LoadingLayout.SUCCESS);
                }else {
                    loading_layout.setStatus(LoadingLayout.ERROR);
                }
            }
        });

        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE|WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

    }

 //同步获取token
    @JavascriptInterface
    public String getLoginUser(Object msg)  {
        String login_token = "";
        if (SharedPreferencesUtil.isLogin()){
            try {
                login_token = URLEncoder.encode(SharedPreferencesUtil.getLoginToken(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return  login_token;
    }

    private void updateKFuState() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(AppUtils.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        HttpPostService httpPostService = retrofit.create(HttpPostService.class);

        Observable<Boolean> observable = httpPostService.updateKeFuMsgState(SharedPreferencesUtil.getLoginToken());

        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Boolean aBoolean) {

                    }

                    @Override
                    public void onError(Throwable e) {
                      //  ToastTools.showPublicToast(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    @Override
    public void loadData() {
       loadWebView();
    }

    private class MyWebChromeClient extends WebChromeClient{

        // For Android < 3.0
        public void openFileChooser(ValueCallback<Uri> valueCallback) {
            mUploadCallBack = valueCallback;
            showFileChooser();
        }

        // For Android  >= 3.0
        public void openFileChooser(ValueCallback valueCallback, String acceptType) {
            mUploadCallBack = valueCallback;
            showFileChooser();
        }

        //For Android  >= 4.1
        public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
            mUploadCallBack = valueCallback;
            showFileChooser();
        }

        // For Android >= 5.0
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
            mUploadCallBackAboveL = filePathCallback;
            showFileChooser();
            return true;
        }
    }

    private void showFileChooser(){
        sheetDialog =  new SheetDialog.Builder(getContext()).setTitle(ConstantsUtils.EMPTY_STR)
                .addMenu("拍照", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (sheetDialog != null && sheetDialog.isShowing()){
                            sheetDialog.dismiss();
                        }
                        if (permissionChecker.isLackPermissions(PERMISSIONS)) {
                            permissionChecker.requestPermissions();
                        } else {
                            cameraPath = SDCardUtils.getSDCardPath() + "/temp.png";
                            File file = new File(cameraPath);
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".provider", file));
                            }else{
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                            }

                            intent.putExtra("return-data", false);
                            intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
                            intent.putExtra("noFaceDetection", true);
                            startActivityForResult(intent, TAKE_CAMERA_PHOTO);
                        }
                    }
                })
                .addMenu("从相册中选择", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (sheetDialog != null && sheetDialog.isShowing()){
                            sheetDialog.dismiss();
                        }
                        if (permissionChecker.isLackPermissions(PERMISSIONS)) {
                            permissionChecker.requestPermissions();
                        } else {
                            startPickPhoto();
                        }
                    }
                }).setCancelListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        clearUploadMessage();
                        sheetDialog.dismiss();
                    }
                }).create();
        sheetDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                clearUploadMessage();
            }
        });
        sheetDialog.show();


    }

    /**
     * webview没有选择文件也要传null，防止下次无法执行
     */
    private void clearUploadMessage() {
        if (mUploadCallBackAboveL != null) {
            mUploadCallBackAboveL.onReceiveValue(null);
            mUploadCallBackAboveL = null;
        }
        if (mUploadCallBack != null) {
            mUploadCallBack.onReceiveValue(null);
            mUploadCallBack = null;
        }
    }

    //选择照片
    private void startPickPhoto(){

        PictureSelector.create(getActivity())
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
//                    .maxSelectNum(3)
                .maxSelectNum(1)
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(3)// 每行显示个数
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
                .isCamera(false)// 是否显示拍照按钮
                .isZoomAnim(false)// 图片列表点击 缩放效果 默认true
                .enableCrop(false)// 是否裁剪
                .compress(true)// 是否压缩
                .glideOverride(260, 260)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

  


    //压缩并上传图片
    private Bitmap bitmap;
    private File uploadFile;
    private void compressPictureUpload(String imagePath){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inPurgeable = true;
        options.inInputShareable = true;
        bitmap = BitmapFactory.decodeFile(imagePath, options);

        Observable.create(new ObservableOnSubscribe<String>() {
                @Override
                public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                    uploadFile = compressImage(bitmap);
                    emitter.onNext(uploadFile.getAbsolutePath());
                }
        }).subscribeOn(Schedulers.computation()).observeOn(Schedulers.newThread()).subscribe(new Consumer<String>() {
                @Override
                public void accept(String temp) throws Exception {
                    upLoad(temp);
                    recycleBitmap(bitmap);
                }
            });
        }

    /*
     * 上传头像
     * */
    public void upLoad(String photoPath){


        File file = new File(photoPath);
        OkHttpClient okHttpClient = new OkHttpClient();


        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"),file);

        MultipartBody fileBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(), requestBody)
                .build();

        Request request = new Request.Builder()
                .url(AppUtils.BASE_URL + "uuuuu/upload")
                .post(fileBody)
                .build();

        Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Logger.e("OwnMessageActivity", "onFailure: "+e.getMessage() );
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Gson gson = new Gson();
                final BaseResultEntity baseResultEntity = gson.fromJson(string, BaseResultEntity.class);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)){
                            String imgUrl = (String) baseResultEntity.getData();
                            Toast.makeText(getContext(), "上传成功了" +imgUrl, Toast.LENGTH_SHORT).show();
                            imgUrl = "img[" + imgUrl + "]";
                            webview.callHandler("sendImageAsyn",new Object[]{imgUrl},new OnReturnValue<Integer>(){
                                @Override
                                public void onValue(Integer retValue) {
                                    ToastTools.showToast(getContext(),"发送成功");
                                }
                            });
                        }else {
                            Toast.makeText(getContext(), baseResultEntity.getMsg()+"    "+baseResultEntity.getCode(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });

            }
        });
    }

    /**
     * 压缩图片（质量压缩）
     * @param bitmap
     */
    public static File compressImage(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 5 * 1024 && options > 10) {  //循环判断如果压缩后图片是否大于500kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            Logger.i("-----------------------------option:" + options);
            if (options > 0) {//options 的范围为0--100
                bitmap.compress(Bitmap.CompressFormat.PNG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            }
            long length = baos.toByteArray().length;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date(System.currentTimeMillis());
        String filename = format.format(date);
        File file = new File(Environment.getExternalStorageDirectory(), filename + ".png");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            try {
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {
                Logger.e(e.getMessage());
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            Logger.e(e.getMessage());
            e.printStackTrace();
        }
        recycleBitmap(bitmap);
        return file;
    }

  
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onDetach() {
        super.onDetach();
       // clearCache();
    }
}
